/*******************************************************************************
*  file    : testdataplugin.cpp
*  created : 07.07.2012
*  author  : Slyshyk Oleksiy (alex312@meta.ua)
*******************************************************************************/

#include "wave_plugin.hpp"
#include <QVector>
#include <QStringList>
#include <QFileInfo>
#include <Wave.h>

#ifndef M_PI
#define M_PI (3.1415926535897932384626433832795)
#endif

QString WaveDataPlugin::name() const
{
    return QString("wave");
}

QStringList WaveDataPlugin::formats() const
{
    QStringList res;
    res << "wav";
    return res;
}

QString WaveDataPlugin::fileFilter() const
{
    return QString("Wave (*.wav)");
}

void WaveDataPlugin::setName(const QString &fileName)
{
    fileName_ = fileName;
}

double WaveDataPlugin::sampleRate() const
{
    if(wave_.isNull())
        return 0.0;

    return wave_->GetSampleRate();
}

QVector<std::complex<double> > WaveDataPlugin::getData()
{
    QVector<std::complex<double> > res;

    if(!wave_.isNull())
        {
            if(wave_->GetBitsPerSample() == 8)
                {
                    const char * data = reinterpret_cast<const char*>(wave_->GetData());
                    res.resize(wave_->GetSize());
                    for(int i = 0; i < res.size(); ++i)
                        res[i] = std::complex<double>(data[i],0);
                }
            if(wave_->GetBitsPerSample() == 16)
                {
                    const qint16 * data = reinterpret_cast<const qint16*>(wave_->GetData());
                    res.resize(wave_->GetSize()/2);
                    for(int i = 0; i < res.size(); ++i)
                        res[i] = std::complex<double>(data[i],0);
                }
        }

    return res;
}

bool WaveDataPlugin::read()
{
    return read(fileName_);
}

bool WaveDataPlugin::read(const QString &fileName)
{
    fileName_ = fileName;
    if(wave_.isNull())
        wave_ = QSharedPointer<CWave>(new CWave);

    return wave_->load(fileName_);
}

void WaveDataPlugin::flush()
{
    if(wave_)
        wave_.reset();
}
